# 作者：一只牛吗
# 2025 年03月 07日 18时 17分 42秒
# 1278599690@qq.com
my_list = 'This is a test string from Andrew'.split()
print(my_list)
print(sorted(my_list))
print(sorted(my_list, key=str.lower))

student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(student_tuples, key=lambda x: x[2])  # lambda函数就是匿名函数，这里按第三个元素排序


class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __repr__(self):  # repr方法和str方法最大的区别是，repr可以非字符串，可以被eval()函数重新构造出对象，常用于调试
        return repr((self.name, self.grade, self.age))


student = [Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'A', 10)]
print(sorted(student, key=lambda x: x.age))
John = Student('john', 'A', 15)
print(John)

# 也可以通过opertor库函数自定义排序
from operator import itemgetter

student_tuples = [('john', 'A', 15), ('janet', 'B', 12), ('dave', 'A', 10)]
sorted_tuples = sorted(student_tuples, key=itemgetter(2))
print(sorted_tuples)
# 还可以实现多列排序
sorted_tuples = sorted(student_tuples, key=itemgetter(1, 2))  # 按第三个元素排序，相同的按第二个元素排序
print(sorted_tuples)
# 用lambda表达式也可以实现多列排序
sorted_tuples = sorted(student_tuples, key=lambda x: (x[1], x[2]))
print(sorted_tuples)
# 如果想实现降序排序，可以用reverse参数
sorted_tuples = sorted(student_tuples, key=itemgetter(2), reverse=True)
print(sorted_tuples)
# lambda函数可以通过加负号实现降序排序
sorted_tuples = sorted(student_tuples, key=lambda x: -x[2])
print(sorted_tuples)
# 还可以用attrgetter函数获取对象的属性排序
from operator import attrgetter

sorted_students = sorted(student, key=attrgetter('grade'))
print(sorted_students)

# 对字典的value排序
my_dict = {'a': ['M', 7], 'b': ['F', 3], 'c': ['M', 9], 'd': ['F', 5]}
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1][1]))
print(sorted_dict)

gameresults = [{'name': 'Alice','win':10,'losses':3, 'score': 85},
               {'name': 'Bob','win':5,'losses':5, 'score': 70},
               {'name': 'Charlie','win':7,'losses':2, 'score': 85},
               {'name': 'David','win':6,'losses':4, 'score': 75},
               {'name': 'Emily','win':8,'losses':3, 'score': 90}]
print('_'*50)
print(sorted(gameresults, key=itemgetter('score', 'win'), reverse=True))